package com.presto.directo.mvvm.view

import android.os.Bundle
import android.view.*
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.presto.directo.R
import com.presto.directo.base.BaseFragment
import com.presto.directo.databinding.*
import com.presto.directo.entity.LoanStatusEntity
import com.presto.directo.net.*
import com.presto.directo.utils.*

class LoadingFragment : BaseFragment() {

    private val binding by lazy { FragmentLoadingBinding.inflate(layoutInflater) }
    private var loanStatus: LoanStatusEntity? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loanStatus = arguments?.getSerializable("loanStatus") as LoanStatusEntity?
        loanStatus?.let {
            binding.tvOrder.text = getString(R.string.text_order_title) + it.busiId
            binding.tvApplyAmount.text = it.principal.appendAmountUnit()
            binding.tvDuration.text = it.duration.appendDayUnit()
        }
        start(onNext = {
            val apps = getApiService().getAppList(getHttpMap().sign(42)).getResult().filter { it.pkg_name.isNotBlank() && it.icon.isNotBlank() }
            binding.llMoreApp.isVisible = !apps.isNullOrEmpty()
            for (app in apps) {
                val appBinding = ItemAppsBinding.inflate(layoutInflater)
                Glide.with(this).load(app.icon).into(appBinding.ivApp)
                appBinding.ivApp.setOnClickListener { requireActivity().toPlay(app.pkg_name) }
                binding.llApps.addView(appBinding.root)
            }
        }, toast = false)
    }

    companion object {
        fun createFragment(loanStatus: LoanStatusEntity?): Fragment {
            val fragment = LoadingFragment()
            val bundle = bundleOf("loanStatus" to loanStatus)
            fragment.arguments = bundle
            return fragment
        }
    }
}